<template>
  <el-dialog
    v-model="dialogVisible"
    title="物料产品选择"
    width="80%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="material-select-container">
      <!-- 左侧树形结构 -->
      <div class="tree-section">
        <el-input
          v-model="searchCategory"
          placeholder="请输入分类名称"
          clearable
          prefix-icon="Search"
        />
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="{
            label: 'label',
            children: 'children'
          }"
          node-key="id"
          highlight-current
          :expand-on-click-node="false"
          :default-expand-all="true"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        >
          <template #default="scope">
            <span>{{ scope.data.label }}</span>
            <span v-if="scope.data.children && scope.data.children.length" style="color: #999">
              ({{ scope.data.children.length }})
            </span>
          </template>
        </el-tree>
      </div>

      <!-- 右侧物料列表 -->
      <div class="material-section">
        <div class="search-bar">
          <el-input
            v-model="searchMaterialCode"
            placeholder="请输入物料编码"
            style="width: 200px; margin-right: 10px;"
          />
          <el-input
            v-model="searchMaterialName"
            placeholder="请输入物料名称"
            style="width: 200px; margin-right: 10px;"
          />
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </div>

        <el-table
          :data="materialList"
          border
          style="width: 100%; margin-top: 15px;"
          height="500"
          @row-click="handleSelect"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="materialCode" label="物料编码" min-width="120" />
          <el-table-column prop="materialName" label="物料名称" min-width="120" />
          <el-table-column prop="specification" label="规格型号" min-width="120" />
          <el-table-column prop="flats" label="单位" width="80" />
          <el-table-column prop="flatsMaterial" label="物料产品" min-width="120" />
          <el-table-column prop="belongClass" label="所属分类" min-width="120" />
          <el-table-column prop="createTime" label="创建时间" min-width="160" />
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import http from '@/api/http'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'select'])

// 对话框可见性
const dialogVisible = ref(false)

// 监听visible属性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
  if (val) {
    // 加载初始数据
    getTreeData()
    getMaterialList()
  }
})

// 监听对话框关闭
watch(dialogVisible, (val) => {
  emit('update:visible', val)
})

// 树形数据
const treeRef = ref(null)
const treeData = ref([])
const searchCategory = ref('')

// 获取树形数据
const getTreeData = async () => {
  try {
    const res = await http.get('/api/MaterialCatalog/GetMaterialCatalog')
    if (res.status === true && res.data) {
      // 确保数据格式正确
      const formatTreeData = (data) => {
        if (!Array.isArray(data)) {
          console.warn('输入数据不是数组:', data)
          return []
        }
        return data.map(item => {
          const formattedItem = {
            id: item.id,
            label: item.label || item.name || item.title || '未命名',
            children: []
          }
          if (Array.isArray(item.children) && item.children.length > 0) {
            formattedItem.children = formatTreeData(item.children)
          }
          return formattedItem
        })
      }
      
      const formattedData = formatTreeData(res.data)
      console.log('格式化后的树形数据:', formattedData)
      treeData.value = formattedData
    }
  } catch (error) {
    console.error('获取物料分类失败:', error)
  }
}

// 树节点过滤方法
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}

// 监听搜索文本变化
watch(searchCategory, (val) => {
  treeRef.value?.filter(val)
})

// 物料列表数据
const materialList = ref([])
const searchMaterialCode = ref('')
const searchMaterialName = ref('')
const selectedCategoryId = ref('')

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取物料列表
const getMaterialList = async () => {
  try {
    const params = {
      pageIndex: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      materialCode: searchMaterialCode.value,
      materialName: searchMaterialName.value,
      categoryId: selectedCategoryId.value
    }
    
    const res = await http.get('/api/MaterialProduct/GetMaterialProduct', params)
    if (res.status === true) {
      materialList.value = res.data.products || []
      pagination.value.total = res.data.totalCount || 0
    }
  } catch (error) {
    console.error('获取物料列表失败:', error)
  }
}

// 处理节点点击
const handleNodeClick = (node) => {
  selectedCategoryId.value = node.id
  getMaterialList()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  getMaterialList()
}

// 处理重置
const handleReset = () => {
  searchMaterialCode.value = ''
  searchMaterialName.value = ''
  selectedCategoryId.value = ''
  handleSearch()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  getMaterialList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  getMaterialList()
}

// 处理选择
const handleSelect = (row) => {
  emit('select', row)
  dialogVisible.value = false
}

// 处理关闭
const handleClose = () => {
  searchMaterialCode.value = ''
  searchMaterialName.value = ''
  selectedCategoryId.value = ''
  pagination.value.currentPage = 1
}

// 初始化
onMounted(() => {
  if (props.visible) {
    getTreeData()
    getMaterialList()
  }
})
</script>

<style lang="scss" scoped>
.material-select-container {
  display: flex;
  gap: 20px;
  height: 600px;
}

.tree-section {
  width: 250px;
  border-right: 1px solid #dcdfe6;
  padding-right: 20px;
  
  .el-input {
    margin-bottom: 15px;
  }
  
  .el-tree {
    height: calc(100% - 55px);
    overflow-y: auto;
  }
}

.material-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  .search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
  }
  
  .el-table {
    flex: 1;
  }
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
